<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryData.query"
            @clear="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="ADDdialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <!-- 只要是第三方提供的组件 我们需要对该组件某一部分进行自定义 用插槽 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="{ row }">
            <!-- {{ row }} -->
            <el-switch v-model="row.mg_state" @change="stateChange(row)">
            </el-switch>
          </template>
        </el-table-column>
        <!-- 三个 button -->
        <el-table-column label="操作" width="180">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEdit(row)"
            ></el-button>
            <el-button
              @click="deleteUser(row)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <el-button
              @click="showSetRoles(row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="ADDdialogVisible"
      width="50%"
      @close="addUserDialogClose"
    >
      <!-- 表单 -->
      <el-form
        :rules="addRule"
        ref="form"
        :model="addUserForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ADDdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="EDITdialogVisible"
      width="50%"
      @close="editUserDialogClose"
    >
      <!-- from 表单 -->
      <el-form
        :rules="addRule"
        ref="editFrom"
        label-width="67px"
        :model="editUserFrom"
      >
        <el-form-item label="用户">
          <el-input v-model="editUserFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EDITdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="setDialogVisible" width="50%">
      <div>
        <p>当前用户为: {{ this.userinfo.username }}</p>
        <p>当前角色为: {{ this.userinfo.role_name }}</p>
        <div>
          分配新角色:
          <el-select v-model="selectValve" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 校验邮箱
    const checkoutEmail = (rule, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('邮箱格式不正确'))
    }
    // 校验手机号
    const checkoutMobile = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('手机号格式不正确'))
    }
    return {
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框 显示隐藏
      ADDdialogVisible: false,
      EDITdialogVisible: false,
      setDialogVisible: false,
      // 添加用户表单的所有数据
      addUserForm: {
        username: 'text',
        password: '123456',
        email: '194220@q.com',
        mobile: '15377015532'
      },
      // 添加用户表单校验规则
      addRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkoutEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkoutMobile, trigger: 'blur' }
        ]
      },

      editUserFrom: {
        username: '',
        email: '',
        mobile: ''
      },
      // 存贮点击分配用户信息
      userinfo: {},
      // 角色列表
      rolesList: {},
      // 记录选中值
      selectValve: ''
    }
  },

  created() {
    // 创建数据方法
    this.getUserList()
  },

  methods: {
    // 获取用户列表数据
    async getUserList() {
      const res = await this.$axios.get('/users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户失败')
      // console.log(res)
      this.total = res.data.total
      this.userList = res.data.users
    },
    // 底部 分页设置
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryData.pagesize = newSize
      this.getUserList()
    },
    // 底部 分页设置2
    handleCurrentChange(val) {
      this.queryData.pagenum = val
      this.getUserList()
    },
    // 开关状态发生变化
    async stateChange(val) {
      // console.log(val)
      const res = await this.$axios.put(
        `/users/${val.id}/state/${val.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
    },
    // 重置添加用户按钮里面的数据
    addUserDialogClose() {
      this.$refs.form.resetFields()
    },
    // 点击 添加事件进行预校验 在发送请求 退出按钮 重新渲染
    addUser() {
      this.$refs.form.validate(async flag => {
        if (!flag) return
        const res = await this.$axios.post('/users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.ADDdialogVisible = false
        this.getUserList()
      })
    },
    // 点击按钮显示编辑层
    showEdit({ username, email, mobile, id }) {
      this.editUserFrom.username = username
      this.editUserFrom.email = email
      this.editUserFrom.mobile = mobile
      this.editUserFrom.id = id
      this.EDITdialogVisible = true
    },
    // 关闭编辑按钮重置内容
    editUserDialogClose() {
      this.$refs.editFrom.resetFields()
    },
    // 完成编辑
    editUsers() {
      this.$refs.editFrom.validate(async flag => {
        if (!flag) return
        const res = await this.$axios.put('users/' + this.editUserFrom.id, {
          email: this.editUserFrom.email,
          mobile: this.editUserFrom.mobile
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.EDITdialogVisible = false
        this.getUserList()
        console.log(res)
      })
    },
    // 点击删除用户
    async deleteUser({ id }) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(async () => {
          const res = await this.$axios.delete(`users/${id}`)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击分配角色
    async showSetRoles(row) {
      this.setDialogVisible = true
      // 获取当前用户信息
      this.userinfo = row
      // 获取角色列表的数据
      const res = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      // console.log(res)
      // console.log(this.rolesList)
    },
    // 记录选中值
    async setRoles() {
      // console.log('1')
      if (this.selectValve === '') return this.$message.error('没有分配新角色')
      const res = await this.$axios.put(`users/${this.userinfo.id}/role`, {
        rid: this.selectValve
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setDialogVisible = false
      // console.log(res)
    }
  }
}
</script>

<style scoped lang='less'>
</style>
